import {ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus} from '@nestjs/common';
import {Result} from "../Result";
import {MyHttpException} from "../exception/MyHttpException";

/**
 * 全局异常过滤器
 */
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();

    console.log('看看拦截的异常：', exception);

    let status, code, msg;

    let flag = (exception instanceof HttpException) ;
    code = flag && (exception instanceof MyHttpException) ? exception?.getCode() : flag ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    status = flag ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    msg = flag ? exception.message : `${exception}`;
    const isSuccess = false;

    response.status(status).json(new Result(isSuccess, code, msg));
  }
}
